export default class SocketService {
  // 实例属性
  ws = null
  // 业务类型和回调函数的对于关系
  callBackMapping = {}
  // 创建单例
  static instance = null
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }

  registerCallBack(socketType, callBack) {
    this.callBackMapping[socketType] = callBack
  }

  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null
  }

  connectRetryCount = 0
  connect() {
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket!')
    }
    this.ws = new WebSocket('ws://localhost:9998')

    this.ws.onopen = () => {
      console.log('WebSocket 连接成功')
      this.connected = true
      // 连接成功之后重置连接数
      this.connectRetryCount = 0
    }
    this.ws.onclose = (e) => {
      console.log('服务器关闭了连接')
      setTimeout(() => {

      }, 200 * this.connectRetryCount)
    }
    // 监听从服务器找那个收到的数据
    this.ws.onmessage = (msg) => {
      console.log('WebSocket 接收到从服务器发来的数据了')
      const recvData = JSON.parse(msg.data)
      const socketType = recvData.socketType
      //   先判断有没有回调函数，即有没有请求数据
      if (this.callBackMapping[socketType]) {
        if (recvData.action === 'getData') {
          //   获取服务端返回的数据
          const realData = recvData.data
          this.callBackMapping[socketType].call(this, JSON.parse(realData))
        } else if (recvData.action === 'fullscreen') {
          this.callBackMapping[socketType].call(this, recvData)
        }
      }
    }
  }

  //  是否已连接成功
  connected = false
  sendRetryCount = 0
  //   发送数据给服务端
  send(data) {
    console.log('发送数据给服务器...')
    if (this.connected) {
      this.sendRetryCount = 0
      this.ws.send(JSON.stringify(data))
    } else {
      setTimeout(() => {
        this.sendRetryCount++
        this.send(data)
      }, 200 * this.sendRetryCount)
    }
  }
}
